package com.leaf.lowcode.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leaf.lowcode.entity.RootPosition;
import com.leaf.lowcode.entity.Rootinfo;
import com.leaf.lowcode.mapper.RootinfoMapper;
import com.leaf.lowcode.utils.RegularInstance;
import com.tencent.welink.iot.SubDeviceDTO;
import com.tencent.welink.iot.WelinkHttp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Component
public class RootStatueSendList {

    @Autowired
    private RootinfoMapper rootInfoMapper;
  @Scheduled(fixedRate = 100)
    public void execute() {
        List<SubDeviceDTO> subDeviceDTOList = RegularInstance.subDeviceDTOList;
        if (subDeviceDTOList != null) {
            for (SubDeviceDTO dto : subDeviceDTOList) {
                String pid = dto.getPid();
                String sn = dto.getSn();
                String din = dto.getDin();
                if ("1701001538".equalsIgnoreCase(pid)) {
                    System.out.println("机器人");
                    QueryWrapper<Rootinfo> wrapper = new QueryWrapper<>();
                    Date startdate = new Date();
                    Date enddate = new Date();
                    startdate.setTime(enddate.getTime()-100);
                    enddate.setTime(enddate.getTime()-2*1000);
                    wrapper.between("date",enddate,startdate);
                    List<Rootinfo> rootInfosnews = rootInfoMapper.selectList(wrapper);
                    Rootinfo rootinfo = rootInfosnews.get(0);
                    Date enddate1 = new Date();
                    enddate.setTime(enddate.getTime()-3*60*1000);


                    wrapper.between("date",enddate,startdate);
                    List<Rootinfo> rootInfos = rootInfoMapper.selectList(wrapper);
                    Iterator<Rootinfo> iterator = rootInfos.iterator();
                    List<RootPosition> rootPositionList=new ArrayList<RootPosition>();
                    RootPosition rootPosition=null;
                    while (iterator.hasNext())
                    {
                        rootPosition = new RootPosition();
                        Rootinfo rootinfo1 = iterator.next();
                        rootPosition.setPositionX(rootinfo1.getPositionX());
                        rootPosition.setPositionY(rootinfo1.getPositionY());
                        rootPosition.setPositionTheta(rootinfo1.getPositionTheta());
                        rootPositionList.add(rootPosition);
                    }



                    JSONObject standardData = new JSONObject();
                    standardData.put("reportTs", System.currentTimeMillis());
                    JSONObject profile = new JSONObject();
                    profile.put("modelId", 200666);
                    profile.put("poiCode", "w0906002");
                    standardData.put("profile", profile);
                    WelinkHttp wh = new WelinkHttp(RegularInstance.registerData1, RegularInstance.loginData);
                    JSONObject properties = new JSONObject();
                    JSONObject propertie = new JSONObject();
                    JSONObject jsontran = new JSONObject();
                    JSONObject position=new JSONObject();
                  //  JSONArray postionlist = new JSONArray();
                    JSONArray PositionList= JSONArray.parseArray(JSON.toJSONString(rootPositionList));
                    System.out.println("rootInfolist1.size()"+PositionList.size());
                    //JSONObject orientationlist=new JSONObject();
                    propertie.put("DeviceId","896002959698169856");
                        //System.out.println("11111111111111");


                    RestTemplate restTemplate = new RestTemplate();
                    HttpHeaders headers = new HttpHeaders();
                    HttpMethod method = HttpMethod.POST;
                    // 以表单的方式提交
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    //添加参数developerId
                  //  MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
                    position.put("x", rootinfo.getPositionX());
                    position.put("y", rootinfo.getPositionY());
                    jsontran.put("position",position);
                    jsontran.put("currentFloor",rootinfo.getCurrentFloor());
                    jsontran.put("positionList",PositionList);

                    String json=JSON.toJSONString(jsontran);
                    System.out.println("json"+json);

                 //   String json=JSONObject.s;
                   // multiValueMap.add("json", json);
                    HttpEntity<String> request = new HttpEntity<>(json, headers);
                    //post请求

                    String url="https://api-gz.welink.qq.com/space/logic/dynamic-api/transform?" +
"token=zP0Q30AVs3tMQSJfYjJla6yy*paiKx_P59C1WpZL1lV6doSqGf1TiOA7i_CAgLzrVSE2hyOnFm*8D7wYUn8cNJVcMJXHsCERhddBubX2rHoOs8nX-2aF8c3Dgte_k0Z8" +
     "&" +
    "projectId=212&iotim_" +
   "ticket=gqNfK-Ln5bEpN59_b9KvUfUlrZm5jFKLSoXUllhCxC-S8xJYOsqJkzmpd7J7rBcJy8zNGcN1cbNWlL_CQAnZTA==";


                    ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, request, String.class);

                    System.out.println(responseEntity.getBody());
                    String  body =responseEntity.getBody();
                    JSONObject jsonObject=JSONObject.parseObject(body);
                    JSONObject  data = (JSONObject) jsonObject.get("data");
                    JSONObject  transformInfo= new JSONObject();
                    transformInfo.put("transformPostion",data.get("position"));
                    transformInfo.put("transformPositionList",data.get("positionList"));



/*                    JSONArray positionListJson= (JSONArray) data.get("positionList");
                    System.out.println("positionListJson"+positionListJson);
                    Double positionX= Double.parseDouble(((JSONObject) data.get("position")).get("x").toString());
                    Double positiony= Double.parseDouble(((JSONObject) data.get("position")).get("y").toString());
                    for(int i=0;i<positionListJson.size();i++)
                    {
                         JSONObject postion= (JSONObject) positionListJson.get(i);
                         System.out.println("postion"+postion);
                        RootPosition rootPosition2=new RootPosition();
                        rootPosition2.setPositionX(Double.parseDouble(postion.get("x").toString()));
                        rootPosition2.setPositionY(Double.parseDouble(postion.get("y").toString()));
                        rootPosition2.setPositionTheta(rootPositionList.get(i).getPositionTheta());
                        rootPositionList.set(i,rootPosition2);
                    }*/
                  PositionList= JSONArray.parseArray(JSON.toJSONString(rootPositionList));
                    System.out.println("PositionList"+PositionList);

                    propertie.put("currentFloor", rootinfo.getCurrentFloor());
                        System.out.println("currentFloor===========>"+rootinfo.getCurrentFloor());
                        propertie.put("powerPercent", rootinfo.getPowerPercent());
                        propertie.put("status", rootinfo.getStatus());
//                        propertie.put("positionX", positionX);
//                        propertie.put("positionY", positiony);

                       propertie.put("positionX", rootinfo.getPositionX());
                       propertie.put("positionY", rootinfo.getPositionY());
                        propertie.put("positionTheta", rootinfo.getPositionTheta());
                        propertie.put("orientationX", rootinfo.getOrientationX());
                        propertie.put("orientationY", rootinfo.getOrientationY());
                        propertie.put("orientationZ", rootinfo.getOrientationZ());
                        propertie.put("orientationW",rootinfo.getOrientationW());
                       propertie.put("PositionList",PositionList);
                       propertie.put("transformInfo",transformInfo);
                        properties.put("Rootinfo", propertie);
                        standardData.put("events", new JSONObject());
                        standardData.put("properties", properties);
                    //standardData.put("properties", "{}");
                    try {
                         System.out.println("上传数据");
                        String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);
                          System.out.println("发送设备运行时事件数据==" + devRunEvent);
                    //        System.out.println("--------------------------------开始传输设备运行时事件数据");
                  wh.sendMessage(RegularInstance.loginData.load(), 80000, Long.parseLong(din), devRunEvent, true);
                    } catch (Exception e) {
                    System.out.println("设备运行时事件数据传输出现异常");
                    }
                }
                }
            }
        }

}